<template>
  <div class="user-manage-container">
    <el-card class="user-card" shadow="hover">
      <div class="header">
        <div class="title-section">
          <h2 class="page-title">
            <el-icon class="title-icon"><User /></el-icon>
            用户管理
          </h2>
          <p class="description">管理系统用户，包括用户名、类型、部门和工作岗位</p>
        </div>
        <el-button type="primary" @click="openDialog()" class="create-btn">
          <el-icon><Plus /></el-icon>
          创建用户
        </el-button>
      </div>

      <!-- 搜索和筛选区域 -->
      <div class="search-section">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索用户名、部门或岗位..."
          class="search-input"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select v-model="filterType" placeholder="用户类型" clearable @change="handleSearch">
          <el-option label="管理员" value="管理员" />
          <el-option label="普通账户" value="普通账户" />
        </el-select>
      </div>

      <!-- 用户表格 -->
      <el-table
        :data="filteredUserList"
        stripe
        border
        class="user-table"
        v-loading="loading"
        empty-text="暂无用户数据"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column prop="Username" label="用户名" min-width="120">
          <template #default="scope">
            <div class="user-info">
              <el-avatar :size="32" class="user-avatar">
                {{ scope.row.Username.charAt(0).toUpperCase() }}
              </el-avatar>
              <span class="username">{{ scope.row.Username }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="userType" label="用户类型" width="120">
          <template #default="scope">
            <el-tag :type="scope.row.userType === '管理员' ? 'danger' : 'primary'" size="small">
              {{ scope.row.userType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="worktype" label="岗位" min-width="120" />
        <el-table-column prop="departement" label="部门" min-width="120" />
        <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="openDialog(scope.row)">
              <el-icon><Edit /></el-icon>
              {{ scope.row.Username === 'admin' ? '修改密码' : '编辑' }}
            </el-button>
            <el-button 
              v-if="scope.row.Username !== 'admin'" 
              size="small" 
              type="danger" 
              @click="handleDelete(scope.row.id)"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户创建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="form.id ? '编辑用户' : '创建用户'"
      width="600px"
      align-center
      :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="formRules" ref="formRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="Username">
              <el-input v-model="form.Username" placeholder="请输入用户名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户类型" prop="userType">
              <el-select v-model="form.userType" placeholder="请选择用户类型" style="width: 100%">
                <el-option label="普通账户" value="普通账户" />
                <el-option label="管理员" value="管理员" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="岗位" prop="worktype">
              <el-input v-model="form.worktype" placeholder="请输入岗位" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门" prop="departement">
              <el-input v-model="form.departement" placeholder="请输入所属部门" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="密码" prop="password" v-if="!form.id">
          <el-input v-model="form.password" type="password" placeholder="设置初始密码" show-password />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="备注信息（选填）" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, Plus, Search, Edit, Delete } from '@element-plus/icons-vue'
import { getUserList, createUser, updateUser, deleteUser } from '../api/user'

const userList = ref([])
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const searchKeyword = ref('')
const filterType = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const formRef = ref()

const form = ref({
  id: null,
  Username: '',
  userType: '普通账户',
  worktype: '',
  password: '',
  remark: '',
  departement: ''
})

const formRules = {
  Username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  userType: [{ required: true, message: '请选择用户类型', trigger: 'change' }],
  worktype: [{ required: true, message: '请输入岗位', trigger: 'blur' }],
  departement: [{ required: true, message: '请输入部门', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

// 生成32位GUID
function generateGUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    const r = Math.random() * 16 | 0
    const v = c === 'x' ? r : (r & 0x3 | 0x8)
    return v.toString(16)
  }).replace(/-/g, '')
}

// 过滤后的用户列表
const filteredUserList = computed(() => {
  let filtered = userList.value
  
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(user => 
      user.Username.toLowerCase().includes(keyword) ||
      user.departement.toLowerCase().includes(keyword) ||
      user.worktype.toLowerCase().includes(keyword)
    )
  }
  
  if (filterType.value) {
    filtered = filtered.filter(user => user.userType === filterType.value)
  }
  
  return filtered
})

// 打开对话框
function openDialog(user = null) {
  if (user) {
    form.value = { ...user, password: '' } // 编辑时不填密码
  } else {
    form.value = {
      id: null,
      Username: '',
      userType: '普通账户',
      worktype: '',
      password: '',
      remark: '',
      departement: ''
    }
  }
  dialogVisible.value = true
}

// 加载用户列表
async function loadUsers() {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value
    }
    const res = await getUserList(params)
    userList.value = res.records || []
    total.value = res.total || 0
  } catch (error) {
    ElMessage.error('加载用户列表失败')
    console.error('加载用户列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索处理
function handleSearch() {
  currentPage.value = 1
  loadUsers()
}

// 分页处理
function handleSizeChange(val) {
  pageSize.value = val
  loadUsers()
}

function handleCurrentChange(val) {
  currentPage.value = val
  loadUsers()
}

// 提交表单
async function handleSubmit() {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    submitLoading.value = true
    try {
      const payload = { ...form.value }
      
      if (!form.value.id) {
        // 创建用户时自动生成GUID
        payload.id = generateGUID()
        await createUser(payload)
        ElMessage.success('用户创建成功')
      } else {
        // 更新用户
        delete payload.password // 不更新密码
        await updateUser(form.value.id, payload)
        ElMessage.success('用户更新成功')
      }
      
      dialogVisible.value = false
      loadUsers()
    } catch (error) {
      ElMessage.error('操作失败，请重试')
      console.error('提交失败:', error)
    } finally {
      submitLoading.value = false
    }
  })
}

// 删除用户
function handleDelete(id) {
  ElMessageBox.confirm('确认删除该用户？此操作不可恢复', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteUser(id)
      ElMessage.success('删除成功')
      loadUsers()
    } catch (error) {
      ElMessage.error('删除失败，请重试')
      console.error('删除失败:', error)
    }
  }).catch(() => {})
}

onMounted(() => {
  loadUsers()
})
</script>

<style scoped>
.user-manage-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.user-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.title-section {
  flex: 1;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.title-icon {
  font-size: 24px;
  color: #409eff;
}

.description {
  margin: 0;
  font-size: 14px;
  color: #909399;
  line-height: 1.5;
}

.create-btn {
  padding: 12px 20px;
  font-weight: 500;
  border-radius: 8px;
}

.search-section {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
  align-items: center;
}

.search-input {
  flex: 1;
  max-width: 300px;
}

.user-table {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-avatar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-weight: 600;
}

.username {
  font-weight: 500;
  color: #303133;
}

.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-table th) {
  background: #f5f7fa !important;
  font-weight: 600;
}

:deep(.el-dialog) {
  border-radius: 12px;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #ebeef5;
  padding: 20px 24px;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid #ebeef5;
  padding: 16px 24px;
}

@media (max-width: 768px) {
  .user-manage-container {
    padding: 10px;
  }
  
  .header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .search-section {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-input {
    max-width: none;
  }
}
</style>
